﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using cmdLineParserModule;

namespace cmdLineParserModule
{
    /// <summary>
    /// Option class for marking double attribute, usable with 'double' or 'double?' only
    /// </summary>
    public class optionDoubleAttribute : optionParametrizedAttribute
    {
        /// <summary>
        /// Minimal value that can be entered by user
        /// </summary>
        public double min = double.MinValue;

        /// <summary>
        /// Maximal value that can be entered by user
        /// </summary>
        public double max = double.MaxValue;

        /// <summary>
        /// Extends custom checking with defaultValue validity
        /// </summary>
        protected override void customCheck()
        {
            base.customCheck();
            checkDefaultValue();
        }

        /// <summary>
        /// Checks correct defaultValue definition (if defined, must be in range of <min, max>)
        /// </summary>
        private void checkDefaultValue()
        {
            if (defaultValue == null)
                return;

            if ((double)defaultValue < min || (double)defaultValue > max)
                throw new WrongDefinitionException("defaultValue {0} is out of range ({1} to {2}).", defaultValue, min, max);
        }

        /// <summary>
        /// Expected type of property marked with this class
        /// </summary>
        /// <returns></returns>
        internal override Type typeAccepted()
        {
            if (choiceRequired)
                return typeof(double);
            else
                return typeof(double?);
        }
 
        /// <summary>
        /// Creates double value from string
        /// </summary>
        /// <param name="stringValue">String containing double value</param>
        /// <returns>Double value from string</returns>
        internal override object createValueFromString(string stringValue)
        {
            double value;
            if (!double.TryParse(stringValue, out value))
                throw new WrongUsageException("Cannot convert {0} to float value.", stringValue);


            if (value < min || value > max)
                throw new WrongUsageException("{0} is out of range ({1} to {2}).", value, min, max);

            return value;
        }
    }
}